<?php

namespace Biz;

use Base\Exception\NoRecordException;

class Coupon extends \Base\BaseBiz
{
    public function returnAwardRes_($user_id){
        $base_orm_model = new  \Base\BaseOrmModel();
        try{
            $base_orm_model->beginTransaction();
            /*获取随机中奖type*/
            $award_type  =$this->getrandstr_($user_id);
            $data_res = array();
            $sort =0;
            foreach ($award_type as $key => $value){
                $data = array();
                if ($value == 1) {
                    //返回一张优惠券 并消耗
                    $coupon_list = new \Orm\Coupon\CouponList();
                    $coupon_list["where"] = "is_use = 0";
                    $coupon_list["limit"] = 1;
                    $coupon_list->load();
                    if (count($coupon_list["lists"])>0) {
                        $coupon_res = $coupon_list["lists"];
                        $coupon_res = reset($coupon_res);
                        $coupon_class = new \Orm\Coupon\CouponClass();
                        $coupon_class->loadById($coupon_res["id"]);
                        $coupon_class["is_use"] = 1;
                        $coupon_class->update();
                        //修改优惠券总库存
                        if ($coupon_class["id"]>0) {
                            $coupon_total = $this->getCouponTotal();
                            $coupon_type_class = new \Orm\CouponType\CouponTypeClass();
                            $coupon_type_class->loadById(1); //默认coupon_type 表中卡券id=1
                            $coupon_type_class["total_num"] =$coupon_total;
                            $coupon_type_class->update();
                            //添加用户中奖日志
                            if ($coupon_type_class["id"]>0) {
                                $winning_log_class = new \Orm\WinningLog\WinningLogClass();
                                $winning_log_class["user_id"] = $user_id;
                                $winning_log_class["memo"] = $coupon_type_class["memo"];
                                $winning_log_class["coupon_type"] = $value;
                                $winning_log_class["coupon_id"] = $coupon_class["id"];
                                $winning_log_class["coupon_code"] = $coupon_class["code"];
                                $winning_log_class["coupon_type_name"] = $coupon_type_class["name"];
                                $winning_log_class->insert();
                            }
                            $data["type"] = $value;
                            $data["memo"] = $this->getmemo();
                            $data["name"] = $coupon_type_class["name"];
                            $data["content"] = $coupon_class["code"];
                            $data["icon_url"] = "http://ziyan-image.oss-cn-hangzhou.aliyuncs.com/guoqi/yhj5.png";
                        }
                    }
                }else{
                    $data = $this->getLinkUrl($value,$user_id);
                }
                if ($data) {
                    $data_res[$sort++]= $data;
                }

            }
            $base_orm_model->commit();
            return $data_res;
        }catch (\Exception $e){
            $base_orm_model->rollBack();
            $data["type"] = "202";
            $data["name"] = "服务器请求人数过多，请稍后再试";
            $data["memo"] = "服务器请求人数过多，请稍后再试";
            $data["icon_url"] = "服务器请求人数过多，请稍后再试";
            return $data;
        }
    }
    /*
     * 返回中奖结果
     */
    public function returnAwardRes($user_id){
        $base_orm_model = new  \Base\BaseOrmModel();
        try{
            $data = array();
            $base_orm_model->beginTransaction();
            /*获取随机中奖type*/
            $award_type  =$this->getrandstr($user_id);
            switch ($award_type){
                case '1':
                    //返回一张优惠券 并消耗
                    $coupon_list = new \Orm\Coupon\CouponList();
                    $coupon_list["where"] = "is_use = 0";
                    $coupon_list["limit"] = 1;
                    $coupon_list->load();
                    if (count($coupon_list["lists"])>0) {
                        $coupon_res = $coupon_list["lists"];
                        $coupon_res = reset($coupon_res);
                        $coupon_class = new \Orm\Coupon\CouponClass();
                        $coupon_class->loadById($coupon_res["id"]);
                        $coupon_class["is_use"] = 1;
                        $coupon_class->update();
                        //修改优惠券总库存
                        if ($coupon_class["id"]>0) {
                            $coupon_total = $this->getCouponTotal();
                            $coupon_type_class = new \Orm\CouponType\CouponTypeClass();
                            $coupon_type_class->loadById(1); //默认coupon_type 表中卡券id=1
                            $coupon_type_class["total_num"] =$coupon_total;
                            $coupon_type_class->update();
                            //添加用户中奖日志
                            if ($coupon_type_class["id"]>0) {
                                $winning_log_class = new \Orm\WinningLog\WinningLogClass();
                                $winning_log_class["user_id"] = $user_id;
                                $winning_log_class["memo"] = $coupon_type_class["memo"];
                                $winning_log_class["coupon_type"] = $award_type;
                                $winning_log_class["coupon_id"] = $coupon_class["id"];
                                $winning_log_class["coupon_code"] = $coupon_class["code"];
                                $winning_log_class["coupon_type_name"] = $coupon_type_class["name"];
                                $winning_log_class->insert();
                            }
                            $data["info"]["type"] = $award_type;
                            $data["info"]["memo"] = $this->getmemo();
                            $data["info"]["name"] = $coupon_type_class["name"];
                            $data["info"]["content"] = $coupon_class["code"];
                            $data["info"]["icon_url"] = "http://ziyan-image.oss-cn-hangzhou.aliyuncs.com/guoqi/yhj5.png";
                            $base_orm_model->commit();
                            return $data;
                        }
                    }
                    break;
                case '2':
                    $data = $this->getLinkUrl($award_type,$user_id);
                    $base_orm_model->commit();
                    return $data;
                    break;
                case '3':
                    $data = $this->getLinkUrl($award_type,$user_id);
                    $base_orm_model->commit();
                    return $data;
                    break;
                default:
                    $winning_log_class = new \Orm\WinningLog\WinningLogClass();
                    $winning_log_class["user_id"] = $user_id;
                    $winning_log_class["memo"] = "未中奖";
                    $winning_log_class["type"] = \Orm\WinningLog\WinningLogClass::NO_WINNING;
                    $winning_log_class->insert();

                    $data["info"]["type"] = "200";
                    $data["info"]["name"] = "谢谢惠顾!";
                    $data["info"]["memo"] = "谢谢惠顾!";
                    $data["info"]["content"] = "谢谢惠顾!";
                    $data["info"]["icon_url"] = "谢谢惠顾!";
                    $base_orm_model->commit();
                    return $data;
                    break;
            }
        }catch (\Exception $e){
            $base_orm_model->rollBack();
            $data["info"]["type"] = "202";
            $data["info"]["name"] = "服务器请求人数过多，请稍后再试";
            $data["info"]["memo"] = "服务器请求人数过多，请稍后再试";
            $data["info"]["icon_url"] = "服务器请求人数过多，请稍后再试";
            return $data;
        }
    }

    //获取链接优惠券
    public function getLinkUrl($type,$user_id){
        try{
            //消耗库存
            $winning_log_class = new \Orm\WinningLog\WinningLogClass();
            $coupon_type_list = new \Orm\CouponType\CouponTypeList();
            $coupon_type_list["where"] = "type = ".$type;
            $coupon_type_list->load();
            if (count($coupon_type_list["lists"])>0) {
                $coupon_type_res = $coupon_type_list["lists"];
                $coupon_type_res = reset($coupon_type_res);
                $coupon_type_class = new \Orm\CouponType\CouponTypeClass();
                $coupon_type_class->loadById($coupon_type_res["id"]);
                $coupon_type_class["total_num"] = $coupon_type_class["total_num"]-1;
                $coupon_type_class->update();
                //记录日志
                if ($coupon_type_class["id"]>0) {
                    $winning_log_class["user_id"] = $user_id;
                    $winning_log_class["memo"] = $coupon_type_class["memo"];
                    $winning_log_class["coupon_type"] = $coupon_type_class["type"];
                    $winning_log_class["coupon_id"] = "";
                    $winning_log_class["coupon_code"] = "";
                    $winning_log_class["coupon_type_name"] = $coupon_type_class["name"];
                    $winning_log_class->insert();
                }
                $icon_img = "";
                if ($type == 2) {
                    $icon_img = "http://ziyan-image.oss-cn-hangzhou.aliyuncs.com/guoqi/djj30.png";
                }else{
                    $icon_img = "http://ziyan-image.oss-cn-hangzhou.aliyuncs.com/guoqi/cpj50.png";
                }
                $data["type"] = $coupon_type_res["type"];
                $data["memo"] = $this->getmemo();
                $data["content"] = $coupon_type_class["link_url"];
                $data["name"] = $coupon_type_class["name"];
                $data["icon_url"] = $icon_img;
                return $data;
            }
        }catch (\Exception $e){
            $data["type"] = "202";
            $data["name"] = "服务器请求人数过多，请稍后再试";
            $data["memo"] = "服务器请求人数过多，请稍后再试";
            $data["icon_url"] = "服务器请求人数过多，请稍后再试";
            return $data;
        }
    }

    //获取中奖type  所有优惠券发完或者卡券发完并且链接优惠券用户已领取三次 返回 error
    public function getrandstr($user_id){
        $str='11111111111111222333';
        $randStr = str_shuffle($str);//打乱字符串
        $rands= substr($randStr,0,1);//返回字符串的一部分
        return self::pubMethod($rands,$str,$user_id);
    }
    public function getrandstr_($user_id){
        $str='11111111111111222222222222222222333333333333333333333';
        $randStr = str_shuffle($str);//打乱字符串
        $rands_one= substr($randStr,0,1);//返回字符串的一部分
        $randStr = str_shuffle($str);//打乱字符串
        $rands_two= substr($randStr,0,1);//返回字符串的一部分
        $randStr = str_shuffle($str);//打乱字符串
        $rands_three= substr($randStr,0,1);//返回字符串的一部分
        return $data = array("0"=>$rands_one,"1"=>$rands_two,"2"=>$rands_three);

    }


    //获取优惠券的总数
    public function getCouponTotal(){
        $coupon_model = new \Orm\Coupon\CouponModel();
        return $coupon_model->getCouponTotal();
    }
    /*获取随机描述*/
    public function getmemo(){
        $str = "123";
        $randStr = str_shuffle($str);//打乱字符串
        $rands= substr($randStr,0,1);//返回字符串的一部分
        $memo_ar = array(
            "1"=>"带上紫燕回家吃饭",
            "2"=>"带上紫燕回家吃饭",
            "3"=>"带上紫燕回家吃饭",
        );
        return $memo_ar[$rands];

    }

    //不可领取重新获取type
    public static function getType($str,$rands,$user_id){
        $str = str_replace($rands,'',$str);
        $randStr = str_shuffle($str);//打乱字符串
        $rands= substr($randStr,0,1);//返回字符串的一部分
        if(strlen($rands) < 1){
            return 'error';
        }
        return self::pubMethod($rands,$str,$user_id);
    }

    public static function pubMethod($rands,$str,$user_id){
        //根据type查找库存量
        $coupon_type_list = new \Orm\CouponType\CouponTypeList();
        $coupon_type_list["where"] = "type = ".$rands;
        $coupon_type_list->load();
        if (count($coupon_type_list["lists"])>0) {
            $coupon_type_res = $coupon_type_list["lists"];
            $coupon_type_res  = reset($coupon_type_res);
            //判断库存不为0,此类型券可以使用
            if ($coupon_type_res["total_num"] > 0 ) {
                //判断券类型是卡券还是连接  1为卡券
                if($rands == 1){
                    // 可领取
                    $coupon_list = new \Orm\Coupon\CouponList();
                    $coupon_list["where"] = "is_use = 0";
                    $coupon_list["limit"] = 1;
                    $coupon_list["order"] = "RAND()"; //随机取出一条记录
                    $coupon_list->load();
                    if (count($coupon_list["lists"])>0) {
                        return $rands;
                    }else{
                        return self::getType($str,$rands,$user_id);
                    }
                }else{
                    $winning_log_list = new \Orm\WinningLog\WinningLogList();
                    $winning_log_list["where"] = "coupon_type = ".$rands."  AND user_id = ".$user_id;
                    $winning_log_list->load();
                    if (count($winning_log_list["lists"]) > 2 ) { //判断是否中奖三次，小于此类型券可以获取
                        //不满足条件 走重新取type
                        return self::getType($str,$rands,$user_id);
                    }else{
                        //满足小于三次，可获取
                        return $rands;
                    }
                }
            }else{
                //库存不足 走重新取type
                return self::getType($str,$rands,$user_id);
            }
        }
    }
    /*
     * 核销优惠券
     */
    public function verificationCoupon($excel_code_res){
        $base_orm_model = new \Base\BaseOrmModel();
        try{
            $base_orm_model->beginTransaction();
            if (count($excel_code_res)>0 && is_array($excel_code_res)) {
                $coupon_list = new \Orm\Coupon\CouponList();
                $coupon_list["where"] = "is_use = 1";
                $coupon_list["limit"] = "99999";
                $coupon_list->load();
                if (count($coupon_list["lists"])>0) {
                    foreach ($excel_code_res as $key => $val){
                        /*去掉标题 和提示栏， 从第三行开始判断数据*/
                        if ($key >2) {
                            //去除code的首尾空格
                            $code = preg_replace('/^(&nbsp;|\s)*|(&nbsp;|\s)*$/', '', $val[1]);
                            $is_exist = $this->isExistCoupon($coupon_list["lists"],$code);
                            if ($is_exist) {
                                $coupon_res = $this->getCouponByCode($code);
                                if (count($coupon_res)>0) {
                                    $coupon_class = new \Orm\Coupon\CouponClass();
                                    $coupon_class->loadById($coupon_res["id"]);
                                    $coupon_class["status"] = 1;
                                    $coupon_class->update();
                                }
                            }
                        }
                    }
                }
            }
            $base_orm_model->commit();
            return true;
        }catch(\Exception $e) {
            $base_orm_model->rollBack();
            return false;
        }

    }
    /*检查优惠券是否已消费*/
    public function isExistCoupon($code_list,$code){
        $exist = false;
        foreach ($code_list as $key => $value){
            if ($value["code"] == $code) {
                $exist = true;
            }
        }
        return $exist;
    }
    /*根据code查找优惠券*/
    public function getCouponByCode($code){
        $coupon_res = array();
        $coupon_list = new \Orm\Coupon\CouponList();
        $coupon_list["where"] = "is_use = 1 AND code = '".$code."'";
        $coupon_list["limit"] = "99999";
        $coupon_list->load();
        if (count($coupon_list["lists"])>0) {
            $coupon_res = $coupon_list["lists"];
            $coupon_res = reset($coupon_res);
        }
        return $coupon_res;
    }
}